#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project ：project
# @FileName：request.py
# @IDE     ：PyCharm
# @Author  ：叶鸟翼
# @Time    ：2022/10/3 18:04
import time
from urllib.parse import urljoin

import requests
from retry import retry

from utils.config import host


class Request:
    """Http请求与响应"""

    def __init__(
            self,
            method, url,
            params=None,
            data=None,
            headers=None,
            cookies=None,
            files=None,
            auth=None,
            proxies=None,
            stream=None,
            json=None,
            timeout=15
    ):
        self.method = method.upper()
        self.url = urljoin(host, url)
        self.headers = headers
        self.cookies = cookies
        self.files = files
        self.data = data
        self.json = json
        self.params = params
        self.auth = auth
        self.timeout = timeout
        self.proxies = proxies
        self.stream = stream

    @property
    def kwargs(self):
        return self.__dict__

    @kwargs.setter
    def kwargs(self, value):
        self.kwargs = value

    def __setitem__(self, key, value):
        self.kwargs[key] = value

    def __getitem__(self, item):
        return self.kwargs[item]

    @retry(tries=3, delay=3)  # 请求异常重试
    def _request(self, method, url, **kwargs):
        """发送请求(内部调用api)

        :param method:
        :param url:
        :param kwargs:
        :return:
        :rtype: requests.Response
        """
        return requests.request(method, url, **kwargs)

    def send_request(self):
        """发送请求(外部调用api)

        :return:
        :rtype: requests.Response
        """
        tries, response = 3, None
        while tries:
            response = self._request(**self.kwargs)
            status_code = response.status_code
            if status_code == 200:
                break

            # 响应状态码非200, 间隔3秒后请求重试
            time.sleep(3)
            tries -= 1

        return response
